package com.dyrnq.seckill.config;

import io.lettuce.core.ClientOptions;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.SocketOptions;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

@Configuration
public class LettuceConfig {

    /**
     * 配置客户端资源
     *
     * @return
     */
    @Bean(destroyMethod = "shutdown")
    ClientResources clientResources() {
        return DefaultClientResources.builder().ioThreadPoolSize(8).computationThreadPoolSize(10).build();
    }


    /**
     * 配置Socket选项
     * keepAlive=true
     * tcpNoDelay=true
     * connectionTimeout=5秒
     *
     * @return
     */
    @Bean
    SocketOptions socketOptions() {
        return SocketOptions.builder().keepAlive(true).tcpNoDelay(true).connectTimeout(Duration.ofSeconds(5)).build();
    }

    /**
     * 配置客户端选项
     *
     * @return
     */
    @Bean
    ClientOptions clientOptions(SocketOptions socketOptions) {
        return ClientOptions.builder().socketOptions(socketOptions).build();
    }

    /**
     * 创建RedisClient
     *
     * @param clientResources 客户端资源
     * @param clientOptions   客户端选项
     * @return
     */
    @Bean(destroyMethod = "shutdown")
    RedisClient redisClient(ClientResources clientResources, ClientOptions clientOptions,
                            @Value("${spring.redis.host}") String host,
                            @Value("${spring.redis.port}") String port
    ) {
        RedisURI uri = RedisURI.builder()
                .withHost(host).withPort(Integer.parseInt(port)).build();
        RedisClient client = RedisClient.create(clientResources, uri);
        client.setOptions(clientOptions);
        return client;
    }


}
